package client.test.ihm;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.MalformedURLException;
import java.rmi.ConnectException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.util.HashMap;
import java.util.Map.Entry;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import serveurChatRMI.rmi.interfaces.InterfaceServeurForum;
import client.test.singleton.SingletonConnexion;

public class IHMSelectionSujet {

	JPanel panel;
	
	public void createSelectWindow() {

		
		JFrame fenetre = new JFrame();
		
		fenetre.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		fenetre.setSize(400, 200);
		fenetre.setLocation(300, 200);
		
		
		
		//creation du panel
		panel = new JPanel();
		panel.setLayout(new FlowLayout());
		
		fenetre.add(panel);
		
		
		updateListOfSubjets(fenetre);
		
		
		fenetre.setVisible(true);
		
	}

	
	private void updateListOfSubjets(final JFrame fenetre) {
		SingletonConnexion connect = SingletonConnexion.getInstance();
		
		InterfaceServeurForum isf = null;
		try {
			
			isf = connect.getServeur();
			
		} catch (ConnectException e1) {
			JOptionPane.showMessageDialog(fenetre, "Impossible de se connecter au serveur :\nProbleme de connexion", "Erreur", JOptionPane.WARNING_MESSAGE);
			e1.printStackTrace();
		} catch (MalformedURLException e1) {
			JOptionPane.showMessageDialog(fenetre, "Impossible de se connecter au serveur :\nL'URL n'est pas valide", "Erreur", JOptionPane.WARNING_MESSAGE);
			e1.printStackTrace();
		} catch (RemoteException e1) {
			JOptionPane.showMessageDialog(fenetre, "Impossible de se connecter au serveur :\nProbleme de connexion au serveur", "Erreur", JOptionPane.WARNING_MESSAGE);
			e1.printStackTrace();
		} catch (NotBoundException e1) {
			JOptionPane.showMessageDialog(fenetre, "Impossible de se connecter au serveur :\nLe serveur n'existe pas", "Erreur", JOptionPane.WARNING_MESSAGE);
			e1.printStackTrace();
		} 
		
		
		HashMap<String, String> listSujets = null;
		try {
			listSujets =  isf.getListSujets();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		
		for (Entry<String, String> e : listSujets.entrySet()){
			JButton send = new JButton(e.getKey());
			panel.add(send);
			send.addActionListener(new OpenChatWindowListnener(e.getValue()));
		}
		
		JButton actualiser = new JButton("Actualiser");
		panel.add(actualiser);
		actualiser.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent arg0) {
				
				panel.removeAll();
				System.out.println("update...");
				updateListOfSubjets(fenetre);
				
			}
		});
		
		
		fenetre.setVisible(true);
		
	}
	
	

}
